<template>
  <div class="sign-table">
    <!-- 签到结果表格 -->
    <el-table
      :data="paginatedList"
      border
      stripe
      size="mini"
      style="width: 100%; margin-bottom: 16px;"
      @selection-change="handleSelectionChange"
      v-loading="tableLoading"
      loading-text="数据加载中..."
    >
      <!-- 选择框列 -->
      <el-table-column
        type="selection"
        width="55"
        align="center"
        :visible="visibleColumns.selection"
      ></el-table-column>

      <!-- 固定列：姓名、证件号、电话 -->
      <el-table-column
        prop="name"
        label="姓名"
        width="100"
        align="center"
        :visible="visibleColumns.name"
      ></el-table-column>
      <el-table-column
        prop="idCard"
        label="证件编号"
        width="180"
        align="center"
        :visible="visibleColumns.idCard"
      ></el-table-column>
      <el-table-column
        prop="phone"
        label="电话"
        width="130"
        align="center"
        :visible="visibleColumns.phone"
      ></el-table-column>
      <el-table-column
        label="签到次数"
        align="center"
        width="100"
        :visible="visibleColumns.signCount"
      >
        <template #default="scope">
          {{ countSigned(scope.row.signStatuses) }}
        </template>
      </el-table-column>
      <el-table-column
        label="未签到次数"
        align="center"
        width="120"
        :visible="visibleColumns.unsignedCount"
      >
        <template #default="scope">
          {{ countUnsigned(scope.row.signStatuses) }}
        </template>
      </el-table-column>

      <!-- 动态签到列（根据signDates循环） -->
      <el-table-column
        v-for="(date, index) in getSignDates()"
        :key="`sign-col-${index}`"
        :label="date"
        align="center"
        :visible="visibleColumns[`sign_${index}`]"
      >
        <template #default="scope">
          <el-tag
            :type="getTagType(scope.row.signStatuses[index])"
            @click="handleSignDetail(scope.row, index)"
            class="tag-clickable"
          >
            {{ scope.row.signStatuses[index] || '-' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 无数据提示 -->
    <div class="no-data" v-if="!tableLoading && filteredList.length === 0">
      <el-empty description="暂无学员签到数据，请检查筛选条件或刷新"></el-empty>
    </div>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredList.length"
      size="mini"
      style="text-align: right; margin-top: 8px;"
      v-if="filteredList.length > 0"
    />
  </div>
</template>

<script>
export default {
  name: "SignTable",
  props: {
    classId: {
      type: String,
      required: true
    },
    activeTab: {
      type: String,
      default: "normal"
    },
    normalSignList: {
      type: Array,
      default: () => []
    },
    practiceSignList: {
      type: Array,
      default: () => []
    },
    searchForm: {
      type: Object,
      default: () => ({
        name: "",
        phone: "",
        idCard: "",
        signStatus: ""
      })
    }
  },
  data() {
    return {
      currentSignList: [],
      tableLoading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      showColumnDialog: false,
      columnLabels: {
        selection: "选择框",
        id: "编号",
        name: "姓名",
        idCard: "证件编号",
        phone: "电话",
        remark: "备注",
        signCount: "签到次数",
        unsignedCount: "未签到次数"
      },
      visibleColumns: {},
      selectedColumns: []
    };
  },
  computed: {
    filteredList() {
      return this.currentSignList.filter(row => {
        if (this.searchForm.name && !row.name.includes(this.searchForm.name)) {
          return false;
        }
        if (this.searchForm.phone && !row.phone.includes(this.searchForm.phone)) {
          return false;
        }
        if (this.searchForm.idCard && !row.idCard.includes(this.searchForm.idCard)) {
          return false;
        }
        if (this.searchForm.signStatus) {
          const signedCount = this.countSigned(row.signStatuses);
          if (this.searchForm.signStatus === "signed" && signedCount === 0) {
            return false;
          }
          if (this.searchForm.signStatus === "unsigned" && signedCount > 0) {
            return false;
          }
        }
        return true;
      });
    },
    paginatedList() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      return this.filteredList.slice(start, end);
    }
  },
  watch: {
    activeTab() {
      this.currentSignList = this.activeTab === "normal"
        ? this.normalSignList
        : this.practiceSignList;
      this.pagination.total = this.currentSignList.length;
      this.initColumnConfig();
    },
    normalSignList() {
      if (this.activeTab === "normal") {
        this.currentSignList = this.normalSignList;
        this.pagination.total = this.currentSignList.length;
        this.initColumnConfig();
      }
    },
    practiceSignList() {
      if (this.activeTab === "practice") {
        this.currentSignList = this.practiceSignList;
        this.pagination.total = this.currentSignList.length;
        this.initColumnConfig();
      }
    },
    searchForm: {
      deep: true,
      handler() {
        this.pagination.currentPage = 1;
        this.pagination.total = this.filteredList.length;
        this.$emit('update:filtered-list', this.filteredList);
      }
    },
    currentSignList() {
      this.initColumnConfig();
    }
  },
  methods: {
    initColumnConfig() {
      const savedColumns = localStorage.getItem("signPageVisibleColumns");
      if (savedColumns) {
        this.visibleColumns = JSON.parse(savedColumns);
      } else {
        const defaultColumns = {
          selection: true,
          id: true,
          name: true,
          idCard: true,
          phone: true,
          remark: true,
          signCount: true,
          unsignedCount: true
        };
        const signDates = this.getSignDates();
        signDates.forEach((_, index) => {
          defaultColumns[`sign_${index}`] = true;
        });
        this.visibleColumns = defaultColumns;
      }
      this.selectedColumns = Object.keys(this.visibleColumns).filter(
        key => this.visibleColumns[key]
      );
      this.syncColumnLabels();
    },
    syncColumnLabels() {
      const signDates = this.getSignDates();
      signDates.forEach((date, index) => {
        this.columnLabels[`sign_${index}`] = date;
      });
    },
    getSignDates() {
      return this.currentSignList.length > 0 ? this.currentSignList[0].signDates : [];
    },
    handleSelectionChange(val) {
      this.$emit('update:selected-rows', val);
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
    },
    saveColumnConfig() {
      Object.keys(this.visibleColumns).forEach(key => {
        this.visibleColumns[key] = false;
      });
      this.selectedColumns.forEach(key => {
        this.visibleColumns[key] = true;
      });
      localStorage.setItem("signPageVisibleColumns", JSON.stringify(this.visibleColumns));
      this.showColumnDialog = false;
      this.$message.success("列配置已保存，刷新后生效");
    },
    handleSignDetail(row, index) {
      const detail = row.signDetails[index] || {};
      this.$emit('show-sign-detail', {
        row,
        date: row.signDates[index],
        status: row.signStatuses[index],
        time: detail.time,
        device: detail.device
      });
    },
    getTagType(status) {
      switch (status) {
        case "已签到":
          return "success";
        case "未签到":
          return "danger";
        case "请假":
          return "warning";
        case "迟到":
          return "info";
        default:
          return "default";
      }
    },
    countSigned(statuses) {
      return statuses.filter(status => status === "已签到").length;
    },
    countUnsigned(statuses) {
      return statuses.filter(status => status === "未签到").length;
    }
  },
  created() {
    this.currentSignList = this.activeTab === "normal"
      ? this.normalSignList
      : this.practiceSignList;
    this.initColumnConfig();
  }
};
</script>

<style scoped>
.sign-table {
  width: 100%;
}

.el-table {
  font-size: 13px;
  margin-bottom: 16px !important;
}

.el-table th {
  background-color: #f5f7fa !important;
  font-weight: 500 !important;
}

.el-tag {
  padding: 2px 6px;
  border-radius: 3px;
  cursor: default;
}

.tag-clickable {
  cursor: pointer;
  transition: all 0.2s;
}

.tag-clickable:hover {
  opacity: 0.8;
}

.remark-input {
  width: 100%;
  border: none;
  padding: 4px 0;
}

.remark-input:focus {
  border-bottom: 1px solid #409eff;
  box-shadow: none;
}

.no-data {
  text-align: center;
  padding: 60px 20px;
}

.el-pagination {
  margin-top: 16px !important;
}

@media (max-width: 768px) {
  .el-table {
    font-size: 12px;
  }

  .el-table-column {
    width: auto !important;
    min-width: 80px;
  }
}
</style>
